package ua.epam.java_bravo.data.jdbc;

import java.sql.*;

public class ResourceManager {
    private static final String JDBC_DRIVER = "org.h2.Driver";
    //Home directory for relative DB path is epam-bravo-2010,
    //not timoshenko_housig!!!
    //many time spend on this problem!!!
    private static final String JDBC_URL =
            "/database/housingDB";
    //            "jdbc:h2:src/main/resources/database/housingDB";
    private static final String JDBC_USER = "sa";

    private static final String JDBC_PASSWORD = null;

    private static Driver driver = null;

    public static synchronized Connection getConnection()
            throws SQLException {
        if (driver == null) {
            try {
                Class jdbcDriverClass = Class.forName(JDBC_DRIVER);
                driver = (Driver) jdbcDriverClass.newInstance();
                DriverManager.registerDriver(driver);
            }
            catch (Exception e) {
                System.out.println("Failed to initialise JDBC driver");
                e.printStackTrace();
            }
        }

        return DriverManager.getConnection(
                JDBC_URL,
                JDBC_USER,
                JDBC_PASSWORD
        );
    }


    public static void close(Connection conn) {
        try {
            if (conn != null) {
                conn.close();
            }
        }
        catch (SQLException sqle) {
            sqle.printStackTrace();
        }
    }

    public static void close(PreparedStatement stmt) {
        try {
            if (stmt != null) {
                stmt.close();
            }
        }
        catch (SQLException sqle) {
            sqle.printStackTrace();
        }
    }

    public static void close(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        }
        catch (SQLException sqle) {
            sqle.printStackTrace();
        }

    }

}
